#!/bin/bash
set -e

echo "开始安装 2RTK Caster..."

# 安装依赖项
echo "安装依赖项..."
sudo apt update
sudo apt install -y build-essential git libevent-dev libssl-dev libyaml-dev

# 创建目录结构
echo "创建目录结构..."
sudo mkdir -p /usr/local/etc/2rtk
sudo mkdir -p /var/log/2rtk

# 编译
echo "编译 2RTK Caster..."
cd caster
make clean || true
make

# 安装二进制文件
echo "安装二进制文件..."
sudo cp bin/caster /usr/local/sbin/

# 安装配置文件（如果不存在）
echo "安装配置文件..."
if [ ! -f /usr/local/etc/2rtk/caster.yaml ]; then
    sudo cp -n ../2rtk-config/caster.yaml /usr/local/etc/2rtk/
fi
if [ ! -f /usr/local/etc/2rtk/sourcetable.dat ]; then
    sudo cp -n ../2rtk-config/sourcetable.dat /usr/local/etc/2rtk/
fi
if [ ! -f /usr/local/etc/2rtk/source.auth ]; then
    sudo cp -n ../2rtk-config/source.auth /usr/local/etc/2rtk/
fi
if [ ! -f /usr/local/etc/2rtk/host.auth ]; then
    sudo cp -n ../2rtk-config/host.auth /usr/local/etc/2rtk/
fi
if [ ! -f /usr/local/etc/2rtk/blocklist ]; then
    sudo cp -n ../2rtk-config/blocklist /usr/local/etc/2rtk/
fi

# 创建用户和组
echo "创建用户和组..."
sudo groupadd -f caster
sudo useradd -r -g caster -s /sbin/nologin -d /nonexistent caster 2>/dev/null || true

# 设置权限
echo "设置权限..."
sudo chown -R root:root /usr/local/etc/2rtk
sudo chmod 644 /usr/local/etc/2rtk/*
sudo chmod 755 /usr/local/etc/2rtk

sudo chown -R caster:caster /var/log/2rtk
sudo chmod 755 /var/log/2rtk

# 安装 systemd 服务
echo "安装 systemd 服务..."
cat > 2rtk-caster.service << EOF
[Unit]
Description=2RTK NTRIP Caster
After=network.target

[Service]
Type=simple
User=caster
Group=caster
ExecStart=/usr/local/sbin/caster -c /usr/local/etc/2rtk/caster.yaml
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

# 安全设置
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF

sudo cp 2rtk-caster.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable 2rtk-caster.service

echo "安装完成！"
echo "配置文件位于: /usr/local/etc/2rtk/"
echo "使用 'sudo systemctl start 2rtk-caster' 启动服务"